
from re import compile as re
from cixar.python.text.indent import shift, measure, ShiftError, tab_length
from cixar.python.text import nonblank

def find_comments(content, leader = ''):
    leader_re = re(r'/\*%s(?=\s|\n)' % leader)
    at = 0
    while content:
        search = leader_re.search(content, at)
        if search:
            start = search.start()
            stop = content.find('*/', start)
            if stop >= 0:
                yield search.end(), stop
                at = stop
            else:
                break
        else:
            break

def scan_comments(content, leader = ''):
    for start, stop in find_comments(content, leader):
        line_start = content.rfind("\n", 0, start)
        depth = line_start < 0 and 0 or measure(content[line_start:start])
        line_stop = content.find("\n", start)
        if line_stop > stop: line_stop = stop
        yield (
            start,
            stop,
            (
                content[start:line_stop].strip() +
                shift(content[line_stop:stop], depth + tab_length) 
            )
        )

def comments(content, leader = ''):
    for start, stop, comment in scan_comments(content, leader):
        yield comment

